package top.pengdong.pictureShare.file.controller;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.pengdong.pictureShare.common.model.R;
import top.pengdong.pictureShare.common.utils.Address;
import top.pengdong.pictureShare.file.pojo.PsFile;
import top.pengdong.pictureShare.file.service.FileService;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @description:
 * @projectName: pictureShare
 * @see: top.pengdong.pictureShare.file
 * @author: pc
 * @createTime: 2022/4/20 18:22
 * @version: 1.0
 */
@RestController
@RequestMapping("api/file")
public class FileController {
	/**
	 * 文件保存地址
	 */
	private String basePath = Address.FILEPATH;

	@Resource
	private FileService fileService;

	@ResponseBody
	@RequestMapping(value = "/upload.json", method = RequestMethod.POST)
	public R fileUpload(MultipartFile[] files) throws IllegalStateException, IOException {
		try {
			if (files.length == 0) {
				R.error("请输入文件数据");
			}
			String[] paths = new String[files.length];
			File file = null;
			for (int i =0 ; i < files.length; ++i) {
				PsFile psFile = new PsFile();
				System.err.println("第" + i + "个文件的大小为" + files[i].getSize());
				psFile.setSize(files[i].getSize());
				System.err.println("第" + i + "个文件是否为空" + files[i].isEmpty());
				psFile.setStatus(1);
				System.err.println("第" + i + "个文件的媒体类型为" + files[i].getContentType());
				psFile.setType(files[i].getContentType());
				System.err.println("第" + i + "个文件的文件名为" + files[i].getName());
				psFile.setName(files[i].getOriginalFilename());
				String strPath = "/" + UUID.randomUUID() +
						files[i].getOriginalFilename().substring(
								files[i].getOriginalFilename().lastIndexOf(".")
						);
				psFile.setImgUrl(strPath);
				paths[i] = strPath;

				// 判断如果是 图片 就会添加水印功能 同时判断大小进行压缩
				file = new File(basePath + strPath);
				files[i].transferTo(file);
				if (files[i].getContentType().equals("image/jpeg") || files[i].getContentType().equals("image/png")) {
					fileService.addLogo(file);
					fileService.compress(file);
				}
				// System.err.println("第" + i + "个文件的源文件名为" + files[i].getOriginalFilename());
				fileService.save(psFile);
			}
			return R.ok().put("result", paths);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("文件过大");
		}

	}
	@GetMapping("/get/{fileName}.{type}")
	public void getFile(@PathVariable String fileName, @PathVariable String type, HttpServletResponse response) throws IOException {

		File file = new File ( basePath + "/" + fileName + "." + type);
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(file);
		} catch (Exception e) {
			response.setContentType("application/json;charset=UTF-8");
			ServletOutputStream out = response.getOutputStream();
			ObjectMapper objectMapper = new ObjectMapper();
			out.write(objectMapper.writeValueAsString(R.error("文件路径错误")).getBytes(StandardCharsets.UTF_8));
			out.flush();
			out.close();
			return;
		}

		// 上传 文件 判断 是图片还是视频
		if ("jpg".equals(type) || "JPG".equals(type)) {
			response.setContentType("image/jpg");
		} else if ("png".equals(type) || "PNG".equals(type)) {
			response.setContentType("image/png");
		} else if ("jpeg".equals(type.toLowerCase())) {
			response.setContentType("image/jpeg");
		} else if ("mp4".equals(type) || "MP4".equals(type)) {
			response.setContentType("video/mp4");
		} else {
			ServletOutputStream out = response.getOutputStream();
			ObjectMapper objectMapper = new ObjectMapper();
			out.write(objectMapper.writeValueAsString(R.error("上传错误")).getBytes(StandardCharsets.UTF_8));
			out.flush();
			out.close();
			return;
		}
//		inline：直接在页面显示
//		attchment：以附件形式下载
		// response.setHeader( "Content-Disposition",String.format("inline;filename=\"%s",fileName + "." + type));
		// headers.add ( "Cache-Control","no-cache,no-store,must-revalidate" );
		// headers.add ( "Pragma","no-cache" );
		response.setHeader( "Expires","1500" );

		response.setHeader("Content-Range", "" + Integer.valueOf(fileInputStream.available() - 1));
		IOUtils.copy(fileInputStream, response.getOutputStream());
		response.flushBuffer();
	}
}
